package com.sunnuwell.demo.service.impl;

import com.sunnuwell.demo.common.exception.AdException;
import com.sunnuwell.demo.constant.Constants;
import com.sunnuwell.demo.entity.Role;
import com.sunnuwell.demo.entity.User;
import com.sunnuwell.demo.repository.RoleRepository;
import com.sunnuwell.demo.service.RoleService;
import com.sunnuwell.demo.service.UserService;
import com.sunnuwell.demo.vo.RoleVo;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @program: entry
 * @description: 资源菜单service
 * @author: Mr.lv
 * @create: 2019-04-28 09:39
 **/
@Service
public class RoleServiceImpl implements RoleService {
    private RoleRepository repository;
    private UserService userService;

    public RoleServiceImpl(RoleRepository repository, UserService userService) {
        this.repository = repository;
        this.userService = userService;
    }

    @Override
    public List<Role> getAllRole() {
        return repository.findAll();
    }

    @Override
    public String saveRole(RoleVo roleVo) throws AdException {
        // 检验参数
        if (!roleVo.volidate()) {
            throw  new AdException(-1,Constants.ErrorMsg.REQUEST_PARAM_ERROR);
        }
        repository.save(new Role(
                roleVo.getRid(),roleVo.getName(),roleVo.getResources()
        ));
        return Constants.ErrorMsg.OPERATION_SUCCESS;
    }

    @Override
    public String deleteRole(RoleVo roleVo) throws AdException {
        if (!roleVo.volidateRid()) {
            throw  new AdException(-1,Constants.ErrorMsg.REQUEST_PARAM_ERROR);
        }
        // 删除角色之前，看看有没有用户绑定，如果有先解绑后删除
        List<User> userList = userService.findAllUser();
        for (User u:userList
             ) {
            if (null != u.getRoleList()) {
                for (Role r: u.getRoleList()
                        ) {
                    if (r.getRid().equals(roleVo.getRid())) {
                        // 说明有绑定关系，直接返回
                        throw new AdException(-1,"该角色已被绑定，请解绑后再删除");
                    }
                }
            }
        }
        Role role = new Role();
        role.setRid(roleVo.getRid());
        repository.delete(role);
        return Constants.ErrorMsg.OPERATION_SUCCESS;
    }
}